<?php
namespace redis;

use app\api\logic\Hx;
use think\Log;

class Message
{

    const CHANNEL='notify_message';

    static function send($msg,$to,$ext=[],$from='system'){
        if(is_numeric($to)){
            $to=\app\api\model\User::where('id',$to)->value('imid');
        }
        if($to){
            $data=[
                'msg'=>$msg,
                'to'=>$to,
                'from'=>$from,
                'ext'=>$ext

            ];
            return Predis::publish(self::CHANNEL,json_encode($data));
        }
        return false;

    }


    /**
     * 订阅消息并转发给环信
     */
    static function sendToHx(){
        Predis::subscribe(self::CHANNEL,function($payload, $channel){

            echo($payload."\n");

            if($channel==self::CHANNEL){
                try{
                    $data=json_decode($payload,true);
                    var_dump($data);
                    //Hx::sendTxtToUser($data['msg'],$data['to'],$data['from'],$data['ext']);
                }catch (\Exception $e){
                    echo $e->getMessage().PHP_EOL;
                    Log::error($e->getMessage());
                }
            }

        });
    }
}
